import { getToken } from './token.js'
import axios from 'axios'

// 开发环境走代理，生产环境用真实地址
 //const isDev = process.env.NODE_ENV === 'production'
//const BASE_URL = isDev ? '/api' : 'http://192.168.10.77:6771'

// 开发环境走代理，生产环境用真实地址
const isDev = process.env.NODE_ENV === 'development'
const BASE_URL = isDev ? '/api' : 'https://admin.caifubang.top/prod-api'



function req(obj) {
	return new Promise((resolve, reject) => {
		const method = obj.method || 'GET'
		const path = obj.url.startsWith('/') ? obj.url : '/' + obj.url
		const url = BASE_URL + path
		const data = obj.data || {}
  
		const header = {
		 'Authorization': 'Bearer '+ getToken()
		}
		
		
		uni.request({
			url,
			data,
			method,
			header,
			success: ((res) => {
				if (res.data.code === 403 || res.data.code === 401) {
					// // 错误处理，返回登录页
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000
					});
					uni.reLaunch({
						url:'/pages/login/login'
					})
				
				} else if (res.data.code != null && res.data.code === 500) {
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000
					});
				}
				if (res.statusCode === 200) {
					resolve(res)
				}
			}),
			fail: ((err) => {
				reject(err)
			})
		})
	})
}
export default req
